import { replaceN } from '@/utils/index';
import { useEffect, useRef } from 'react';
import Typed from 'typed.js';
function Typewriter({ text, className, onComplete, scrollToBottom, spend = 20 }) {
  const el = useRef(null);

  useEffect(() => {
    //将text的\n替换为<p></p>包裹
    let newtext = replaceN(text);

    //Typed实现带标签的打字效果
    const options = {
      strings: [newtext],
      typeSpeed: spend,
      showCursor: false,
      contentType: 'html',
      onBegin: () => {},
      onComplete: () => {
        if (typeof onComplete === 'function') {
          onComplete(); //如果外部有传入 执行
        }
      },
    };
    if (typeof scrollToBottom === 'function') {
      setTimeout(() => {
        scrollToBottom();
      }, 2000);
    }

    const typed = new Typed(el.current, options);

    return () => {
      typed.destroy();
    };
  }, [text, onComplete]);

  return <div ref={el} className={className}></div>;
}

export default Typewriter;
